<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="项目编号"> {{ formState?.bh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="项目名称"> {{ formState?.mc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="规格">{{ formState?.gg || '-' }}</a-descriptions-item>
          <a-descriptions-item label="单位">{{ formState?.dw || '-' }}</a-descriptions-item>
          <a-descriptions-item label="单价">{{ formState?.dj || '-' }}</a-descriptions-item>
          <a-descriptions-item label="创建人">{{ formState?.createUser || '-' }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formState?.createTime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <div class="flex justify-start"></div>
      <BaseTable
        :data-source="dataSource"
        column-code="00001141"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
        :loading="loading"
        max-fill
        :extra-height="40"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'itemName'">
            <EditCell>
              <SelectTable v-model:value="record.itemName" type="服务" @select="(medicine) => onSelectMedicine(medicine, record)" />
            </EditCell>
          </template>

          <template v-if="column.dataIndex === 'sl'">
            <EditCell>
              <a-input v-model:value="record.sl" v-input:int class="text-right" placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'memo'">
            <EditCell>
              <a-input v-model:value="record.memo" placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <!-- <ConfirmModal @confirm="onDelete(record)">
              <a-button type="text" danger size="small">删除</a-button>
            </ConfirmModal> -->
            <a-switch v-model:checked="record.status" @change="editRow(record)" />
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button type="primary" class="mr-2" ghost @click="addRow()"> 新增明细 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import BaseTable from '@/components/BaseTable'
import SelectTable from '@/components/SelectTable'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const formState = ref({})
const loading = ref(false)
const dataSource = ref([])
const route = useRoute()
const router = useRouter()
const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row) => {
  row.sfxmbBh = formState.value.bh
  row.status = row.status ? 1 : 0
  if (row.sl <= 0) {
    return message.error('次数不能小于0')
  }
  delete row.mc
  const { code, msg } = await post('/course/serviceItemAssociation/doSaveServiceItemAssociation', row)
  if (code !== 0) return message.error(msg || '操作失败')
  getDetailData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (item.itemCode && item.sl) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

const onSelectMedicine = (medicine, row) => {
  row.itemName = medicine?.itemName
  row.duration = medicine?.duration
  row.dw = medicine?.dw
  row.zjm = medicine?.zjm
  row.sl = 1
  row.itemCode = medicine?.itemCode
  editRow(row)
}
//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true }
  dataSource.value.push(addRow)
}
const getMainData = async () => {
  const { data, code } = await post('/course/serviceItemAssociation/getClinicalDictInfoList', {
    bh: route.query?.bh
  })
  if (code === 0) {
    formState.value = {
      ...data[0],
      dj: parseFloat(data[0].dj).toFixed(3)
    }
  }
}
const getDetailData = async () => {
  loading.value = true
  const { data, code } = await post('/course/serviceItemAssociation/getServiceItemAssociation', {
    sfxmbBh: route.query?.bh,
    pageNum: 1,
    pageSize: 999
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data.map((item) => {
      return {
        ...item,
        status: item.status === 1 ? true : false
      }
    })
  }
}
// const onDelete = async (row) => {
//   if (row.id) {
//     const { code, msg } = await post('/course/serviceItemAssociation/doDelServiceItemAssociation', {
//       id: row?.id
//     })
//     if (code !== 0) return message.error(msg || '删除失败')
//     message.success(msg)
//     getDetailData()
//   } else {
//     dataSource.value = dataSource.value.filter((item) => {
//       return item.key !== row.key
//     })
//     message.success('删除成功')
//   }
// }
watchEffect(() => {
  if (route.query?.bh) {
    getMainData()
    getDetailData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-card-head) {
  padding-left: 8px;
}
</style>
